//
//  SSEmoticonViewController.swift
//  SSEmoticon
//
//  Created by stevenSu on 15/8/5.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit

class SSEmoticonViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }
    
    init(selEmoticonCallBack: (emoticon: SSEmoticon) -> Void) {
        super.init(nibName: nil, bundle: nil)
        selectedEmoticonCallBack = selEmoticonCallBack
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var selectedEmoticonCallBack: ((emoticon: SSEmoticon) -> Void)?
    
    private lazy var packages = SSEmoticonPackage.packages
    private lazy var emojiView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmojiViewFlowLayout())
    private lazy var toolbar = UIToolbar()
    
    private func setupUI() {
        view.addSubview(emojiView)
        view.addSubview(toolbar)
        let dict = ["emoji": emojiView, "tool": toolbar]
        emojiView.translatesAutoresizingMaskIntoConstraints = false
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[emoji]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tool]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[emoji]-0-[tool(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))

        prepareEmojiView()
        prepareToolbar()
    }
    
    private func prepareEmojiView() {
        emojiView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        emojiView.registerClass(EmojiViewCell.self, forCellWithReuseIdentifier: cellType)
        emojiView.dataSource = self
        emojiView.delegate = self
    }
    
    private func prepareToolbar() {
        toolbar.tintColor = UIColor.darkGrayColor()
        var arrayM = [UIBarButtonItem]()
        var index = 0
        for package in packages {
            
            let item = UIBarButtonItem(title: package.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "selectBtn:")
            item.tag = index++
            arrayM.append(item)
            arrayM.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        arrayM.removeLast()
        toolbar.items = arrayM
    }
    
    func selectBtn(item: UIBarButtonItem) {
        emojiView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: item.tag), atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
  
}

private var cellType = "emoticon"

extension SSEmoticonViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellType, forIndexPath: indexPath) as! EmojiViewCell
        
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

        let emoticon = packages[indexPath.section].emoticons[indexPath.item]
        selectedEmoticonCallBack!(emoticon: emoticon)
        if indexPath.section != 0 && emoticon.isRemoveBtn == false {
            emoticon.clickCount++
            SSEmoticonPackage.saveRecentEmoticon(emoticon)
            collectionView.reloadSections(NSIndexSet(index: 0))
        }
    }
}

private class EmojiViewFlowLayout: UICollectionViewFlowLayout {
    private override func prepareLayout() {
        let w = UIScreen.mainScreen().bounds.width / CGFloat(7)
        let margin = (collectionView!.bounds.height - 3 * w) * 0.499
        itemSize = CGSize(width: w, height: w)
        sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
    }
}

private class EmojiViewCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareButton()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var button = UIButton()
    var emoticon: SSEmoticon? {
        didSet {
            let title = emoticon!.emojiString ?? ""
            button.setTitle(title, forState: UIControlState.Normal)
            
            if emoticon!.isRemoveBtn {
                button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            } else {
                let image = emoticon!.pngPath != nil ? UIImage(contentsOfFile: emoticon!.pngPath!) : nil
                button.setImage(image, forState: UIControlState.Normal)
            }
        }
    }
    
    private func prepareButton() {
        contentView.addSubview(button)
        button.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        button.frame = CGRectInset(bounds, 5, 5)
        button.titleLabel?.font = UIFont.systemFontOfSize(32)
        button.userInteractionEnabled = false
    }
    
}
